<script>
import QuarterlyAccountSearchForm from '@/mixins/quarterly-account-search-form'
import TableMixin from './table-mixin'
import QuarterlyAccountDetails from '@/mixins/quarterly-account-details'
import { TABLE_REPORTED, TABLE_RESOLVED, TABLE_REJECTED, TABLE_UNDER_REPORT, TABLE_UNDER_REPORT_TEXT, TABLE_REPORTED_TEXT } from '@/config'
import { simpleAoa2Sheet } from '@/utils/sheet'
import pick from 'lodash/pick'
import AreaPicker from '@/components/area-picker'
import DictionaryPicker from '@/components/dictionary-picker'
import { statusEnergyConsumptionStructureSchedule } from '@/api/enterpriseQuarterlyReport'

export default {
  name: 'quarterly-account',
  mixins: [QuarterlyAccountSearchForm, TableMixin, QuarterlyAccountDetails],
  components: { AreaPicker, DictionaryPicker },
  data() {
    return {
      tableStatus: '',
      areaCode: '',
      energyConsumptionLevel: '',
      reportState: '',
      reportStateList: [
        { label: TABLE_UNDER_REPORT_TEXT, value: TABLE_UNDER_REPORT },
        { label: TABLE_REPORTED_TEXT, value: TABLE_REPORTED },
      ]
    }
  },
  computed: {
    showButton() {
      const status = String(this.tableStatus)
      // 显示通过/驳回按钮的条件
      // 只有表状态是 已上报 才可以通过或驳回

      // 2024-1-19 去掉审核功能
      return status === TABLE_REPORTED
    },
    exportable () {
      return this.tableStatus === TABLE_RESOLVED;
    },
    enterpriseText() {
      const enterprise = this.enterprise
      const enterpriseList = this.enterpriseList
      return (enterpriseList.find(v => +v.id === +enterprise) || {}).name
    }
  },
  methods: {
    async auditTable (status, reason = '') {
      try {
        await statusEnergyConsumptionStructureSchedule({
          tenantId: this.enterpriseId,
          tableId: this.tableAccountId,
          reportStatus: status,
          year: this.year,
          quarter: this.quarter,
          illustrate: reason,
        })
        this.$message.success('操作成功')

        // 暂存、上报、通过、驳回后返回（刷新）
        this.back(true)
      } catch (e) {
        console.warn(e)
      }
    },
    resolve() {
      this.auditTable(TABLE_RESOLVED)
    },
    reject() {
      this.$prompt('退回理由：', '提示', {
        closeOnClickModal: false,
        inputPattern: /\S+/,
        inputPlaceholder: '请输入退回理由'
      }).then(({ value }) => {
        this.auditTable(TABLE_REJECTED, value)
      }).catch(() => { })
    },
    exportExcel() {
      const year = this.year
      const quarter = this.quarter
      const enterpriseName = this.enterpriseText || ''
      const columns = this.columns
      const lists = this.lists
      const headers = columns.map(v => v.label)
      const fileName = `${enterpriseName}${year}年第${quarter}季度企业季度报表填报情况一览表.xlsx`
      const data = lists.map((v) => pick(v, columns.map(col => col.prop)))
      const aoa = [
        headers,
        ...data.map(item => {
          return columns.map(v => {
            return v.prop.indexOf('table') > -1
              ? this.statusText(item[v.prop])
              : (item[v.prop] || '');
          })
        }),
      ]

      simpleAoa2Sheet(aoa, fileName)
    },
    exportData () {
      const quarterlyAccountTable = this.$refs.quarterlyAccountTable
      const flattenColumns = quarterlyAccountTable.flattenColumns
      const lists = quarterlyAccountTable.getData() || [];
      const summary = this.$refs.quarterlyAccountTable?.summary
      const informer = this.$refs.quarterlyAccountTable?.getInformer?.()

      const fill = (v) => flattenColumns.map(col => {
        const prop = col.prop
        return v[prop] || ''
      })

      const aoa = [
        (flattenColumns || []).map(v => v.label),
      ]

      lists.forEach(v => {
        const data = fill(v)
        // console.log(data);
        aoa.push(data)
      })

      // 合计
      if (summary) {
        const d = summary.data.reduce((acc, v) => {
          acc[v.key] = String(v.value || '')
          return acc
        }, {})
        const data = fill(d)
        aoa.push(data)
      }

      // 本年综合能源消费量（当量值）
      // 上年综合能源消费量（当量值）
      // consumptionLastYear consumptionThisYear
      const consumptionThisYear = this.$refs.quarterlyAccountTable?.currentValue
      const consumptionLastYear = this.$refs.quarterlyAccountTable?.previousValue
      if (consumptionLastYear != null && consumptionThisYear != null) {
        aoa.push([])
        aoa.push(
          ['本年综合能源消费量（当量值）', consumptionThisYear || '', '上年综合能源消费量（当量值）', consumptionLastYear || '']
        )
      }

      const appendInformant = v => ([
        fill({}),
        fill([]),
        ['填报负责人：', v.personInCharge, '填报人：', v.informer, '电话：', v.telephone, '填报日期：', v.fillInDate],
      ])
      aoa.push(
        ...appendInformant(informer)
      )

      const fileName = `${this.year}年第${this.quarter}季度${this.tableName}.xlsx`
      simpleAoa2Sheet(aoa, fileName)
    },
  },
}
</script>

<template>
  <div class="padding flex direction-column width-100 height-100">
    <div class="search-form">
      <el-form inline>
        <el-form-item label="所属区域">
          <area-picker v-model="areaCode"></area-picker>
        </el-form-item>
        <el-form-item label="企业">
          <el-select v-model="enterprise" filterable clearable>
            <el-option v-for="option in enterpriseList" :key="option.id" :label="option.name"
              :value="option.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年能耗等级">
          <dictionary-picker v-model="energyConsumptionLevel" dic-code="NENG_HAO_SHUI_PING"></dictionary-picker>
        </el-form-item>
        <el-form-item label="填报状态">
          <el-select v-model="reportState" filterable clearable>
            <el-option v-for="item in reportStateList" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年份">
          <el-date-picker type="year" :clearable="false" v-model="year" placeholder="选择年份" value="yyyy"
            value-format="yyyy"></el-date-picker>
        </el-form-item>
        <el-form-item label="季度">
          <el-select v-model="quarter" clearable placeholder="请选择季度">
            <el-option v-for="option in options" :key="option.value" v-bind="option"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button type="primary" icon="el-icon-download" @click="exportExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table v-loading="loading" class="table" :data="lists" height="100%" :row-style="rowStyle" :header-cell-style="{
      color: 'white',
      backgroundColor: themeColor,
    }">
      <div slot="empty" class="empty-lists">
        <svg-icon name="search"></svg-icon>
        <span class="empty-text">暂无数据</span>
      </div>
      <el-table-column v-for="column in columns" :key="column.prop" v-bind="column">
        <template v-if="column.prop.indexOf('table') > -1" #default="{ row }">
          <el-link style="font-size: 12px;" :disabled="linkType(row[column.prop]) === 'warning'"
            :type="linkType(row[column.prop])" @click="edit(row, column.tableAccountId)">
            {{ statusText(row[column.prop]) }}
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="showTableAccount" class="padding table-account-details">
      <component :is="tableComponent" ref="quarterlyAccountTable" :year="year" :quarter="quarter" :name="tableName"
        :columns="tableColumns" :t-id="tableAccountId" :enterprise-name="enterpriseName" :enterprise-id="enterpriseId"
        :is-government="true" readonly>
        <template #title="{ title }">
          <div class="padding-horizontal flex align-center">
            <el-button type="primary" icon="el-icon-back" circle @click="back(true)"></el-button>
            <h2 class="margin-horizontal-auto" style="font-weight: normal;">{{ title }}</h2>
            <template v-if="showButton">
              <el-button type="primary" @click="resolve">通过</el-button>
              <el-button type="danger" @click="reject">退回</el-button>
            </template>
            <el-button v-if="exportable" type="primary" @click="exportData">导出</el-button>
          </div>
        </template>
      </component>
    </div>
  </div>
</template>

<style scoped>
.table-account-details {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
</style>
